package com.study.d015propertybind.fx;

import javafx.application.Application;
import javafx.beans.binding.ObjectBinding;
import javafx.beans.property.SimpleListProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
 * @description 集合绑定中valueAt()方法的使用
 * valueAt() 返回的是一个绑定对象
 * @author xtayhame date 2020年3月6日 version since v1.0
 */
public class ValueAtMethodMain extends Application {
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws Exception {
		ObservableList<String> list=FXCollections.observableArrayList();
		list.addAll("A","B","C","D");

		SimpleListProperty<String> listProperty = new SimpleListProperty<String>(list);


		AnchorPane anchorPane = new AnchorPane();

		HBox hBox =new HBox(5);
		TextField t1 = new TextField();
		TextField t2 = new TextField();

		hBox.getChildren().addAll(t1,t2);

		VBox vBox = new VBox();

		VBox listData = new VBox();
		listData.setSpacing(10);
		for(int i=0;i<list.size();i++){
			Label label = new Label();
			ObjectBinding<String> obj=listProperty.valueAt(i);
			//将label的值绑定到列表的索引值上
			label.textProperty().bind(obj);
			label.setFont(new Font(30));
			listData.getChildren().add(label);
		}

		t2.textProperty().addListener(new ChangeListener<String>() {
			@Override
			public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
				int index = Integer.parseInt(t1.getText());
				//修改列表的值
				list.set(index, newValue);
			}
		});

		vBox.getChildren().addAll(hBox, listData);

		anchorPane.getChildren().add(vBox);
		stage.setScene(new Scene(anchorPane, 400, 500));
		stage.show();
	}
}
